package com.xpgk.sbwx.beingServed;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.bouncycastle.asn1.eac.Flags;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.template.ext.directive.Str;
import com.xpgk.mvc.base.BaseController;
import com.xpgk.mvc.bentryRegister.Customer;
import com.xpgk.mvc.bentryRegister.CustomerDetail;
import com.xpgk.mvc.bentryRegister.CustomerProduct;
import com.xpgk.mvc.bentryRegister.CustomerProductSurplus;
import com.xpgk.mvc.binShopService.BinShopServiceService;
import com.xpgk.mvc.binShopService.CustomerService;
import com.xpgk.mvc.binShopService.ServiceShaping;
import com.xpgk.mvc.codeSet.Code;
import com.xpgk.mvc.organization.Organization;
import com.xpgk.mvc.productOrgExperience.ProductOrgExperience;
import com.xpgk.mvc.productOutin.ProductOutin;
import com.xpgk.mvc.productSet.Product;
import com.xpgk.mvc.productStock.ProductStock;
import com.xpgk.mvc.productStock.ProductStockInfo;
import com.xpgk.mvc.statistic.dailyTotalStatistic.DailyNursingTotal;
import com.xpgk.mvc.statistic.monthTotalStatistic.MonthTotal;
import com.xpgk.mvc.statistic.yearTotalStatistic.YearTotal;
import com.xpgk.mvc.user.User;
import com.xpgk.tools.ToolDateTime;
import com.xpgk.tools.ToolRandoms;

public class WXBeingServedController extends BaseController {
	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(WXBeingServedController.class);

	private BinShopServiceService binShopServiceService = new BinShopServiceService();

	public void index() {
		
		render("/sbwx/parts.jsp");
	}

	public void queryUser(){
		String organids = getPara("organids");
		Map<String, Object> m = new HashMap<String, Object>();
		String sql = "SELECT * FROM sys_user WHERE organizationids = ? and `status` = '1'";
		if(organids!=null && !organids.equals("")){
			 String currentName = "";
		     String currentCode = "";
		     JSONObject jsonObject = new JSONObject();
		    
			List<User> users = User.dao.find(sql,organids);
			for(int i = 0;i<users.size();i++){
				 User item = users.get(i);
				 currentName = item.getStr(User.column_name);
				 currentCode = item.getStr(User.column_ids);   
		         jsonObject.put(currentCode, currentName);
				
			}
			m.put("user", jsonObject);
			m.put("msg", "200");
		}else{
			m.put("msg", "请先去顾客绑定绑定手机号！");
		}
		 
		renderJson(m);
	     
	}
	
	
	
	@Before(Tx.class)
	public void updateSer() throws ParseException {
	
		Map<String, Object> m = new HashMap<String, Object>();
		String openid = getPara("openid");
		String organids = getPara("organids");
		String yzm = getPara("yzm");
		String sf = getPara("sfuser");
		String yb = getPara("ybuser");
		String gb = getPara("gbuser");
		String dt = getPara("dtuser");
		String xt = getPara("xtuser");
		String yt = getPara("yt");
		String ytid = Code.proYt_ids;
		float ybjyusage = 0f;
		float ybgusage = 0f;
		float gbjyusage = 0f;
		float gbgusage = 0f;
		float dtjyusage = 0f;
		float dtgusage = 0f;
		float xtjyusage = 0f;
		float xtgusage = 0f;
		float jysum = 0f;
		float gsum = 0f;
		boolean flag = true;
		String usageSql = "SELECT * from sb_product_orgexperience WHERE organIds = ?  AND productIds = ? and dataStatus = '1'";
		String proSql = "SELECT * FROM sb_customer_product WHERE customerID = ? AND organids = ? AND productID = ? AND dataStatus in ('1','2')";
		String sql2 = "SELECT * FROM sb_customer where openid = ? AND dataStatus in ('1','2')";
		Customer cus2 = Customer.dao.findFirst(sql2,openid);
		String msg = "200";
		// 药贴 产品表 c3df895ee3b24d1193cb8156edc665b7
		//结束服务，药贴出库
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String date = sdf.format(new Date());
		String serviceSql = "SELECT * from sb_customer_service WHERE customerID = ? and DATE_FORMAT(startTime, '%Y-%m-%d') = ? and dataStatus in ('1','2')";
		Organization org = Organization.dao.findById(organids);
		if(org!=null && org.getStr(Organization.column_todayyzm)!=null && org.getStr(Organization.column_todayyzm).equals(yzm)){
			
		if(cus2!=null){
			String customerIds = cus2.getStr(Customer.column_ids);
			CustomerService cd = CustomerService.dao.findFirst(serviceSql,customerIds,date);
			if(cd!=null){
				if(cd.getInt(CustomerService.column_plasterCount)!=null || cd.getDate(CustomerService.column_endTime)!=null ||cd.getStr(CustomerService.column_isShaping)!=null ||cd.getStr(CustomerService.column_plasterServier)!=null ){
					msg = "今天的精护部位已经保存，如需修改请联系店员";
				}else{
					
					if (Integer.parseInt(yt) > 0) {
						Product p = Product.dao.findById(ytid);
						String pstSql = getSqlMy(ProductStock.sqlId_selPSByOidsAndPids);
						ProductStock pst = ProductStock.dao.findFirst(pstSql,organids, p.getStr(Product.column_ids));
						if (pst != null && pst.getFloat(ProductStock.column_num) >= 1) {
							cd.set(CustomerService.column_plasterCount, yt);
							Date date1 = new Date();
							Date startTime = cd.getDate(CustomerService.column_startTime);
							
							if(sdf.format(date1).equals(sdf.format(startTime))) {  
								 cd.set(CustomerService.column_endTime, date1);
							 }else{
								 cd.set(CustomerService.column_endTime, sdf.parse(sdf.format(startTime)+" 21:00:00"));
							 }
							
							cd.set(CustomerService.column_updateDate, new Date());
							cd.set(CustomerService.column_updateId, customerIds);
							m.put("msg", cd.update());
							// 保存药贴出库记录
							ProductOutin po = new ProductOutin();
							po.set(ProductOutin.column_ids, ToolRandoms.getUuid(true))
									.set(ProductOutin.column_organIds, organids)
									.set(ProductOutin.column_typeIds, p.getStr(Product.column_typeIds))
									.set(ProductOutin.column_productIds, p.getStr(Product.column_ids))
									.set(ProductOutin.column_number, Integer.parseInt(yt)).set(ProductOutin.column_price, 0)
									.set(ProductOutin.column_date, new Date()).set(ProductOutin.column_style, "1")
									.set(ProductOutin.column_createDate, new Date())
									.set(ProductOutin.column_createId, customerIds)
									.set(ProductOutin.column_userIds, customerIds)
									.set(ProductOutin.column_isgk, 1).set(ProductOutin.column_gxsj, new Date());
							if (!po.save()) {
								log.debug("保存" + p.getStr(Product.column_name) + "出库记录失败！！");
								throw new RuntimeException("保存" + p.getStr(Product.column_name) + "出库记录失败！！");
							}
							// 更新产品库存
							// 根据日期和机构id,产品id查出当日是否有库存记录
							String pstInsql = getSqlMy(ProductStockInfo.sqlId_selByOidsAndPidsAndTime);
							ProductStockInfo psi = ProductStockInfo.dao.findFirst(pstInsql, organids,
									p.getStr(Product.column_ids), new Date());

							float num1 = pst.getFloat(ProductStock.column_num) - Float.parseFloat(yt);
							pst.set(ProductStock.column_num, num1).set(ProductStock.column_gxsj, new Date());
							if (!pst.update()) {
								log.debug("更新产品总库存失败");
								throw new RuntimeException("更新产品总库存失败!");
							}
							if (psi != null) {
								// 库存详细信息减少库存
								float num = psi.getFloat(ProductStockInfo.column_stock) - Float.parseFloat(yt);
								psi.set(ProductStockInfo.column_stock, num).set(ProductStockInfo.column_gxsj, new Date())
										.set(ProductOutin.column_updateDate, new Date())
										.set(ProductOutin.column_updateId, customerIds)
										.set(ProductOutin.column_isgk, 1).update();
							} else {
								ProductStockInfo psInfo = new ProductStockInfo();
								String psinfoids = ToolRandoms.getUuid(true);
								psInfo.set(ProductStockInfo.column_ids, psinfoids)
										.set(ProductStockInfo.column_organids,organids)
										.set(ProductStockInfo.column_productID, p.getStr(Product.column_ids))
										.set(ProductStockInfo.column_type, p.getStr(Product.column_typeIds))
										.set(ProductStockInfo.column_stock, pst.getFloat(ProductStock.column_num))
										.set(ProductStockInfo.column_createDate, new Date())
										.set(ProductStockInfo.column_createId, customerIds)
										.set(ProductStockInfo.column_isgk, 1)
										.set(ProductStockInfo.column_gxsj, new Date());
								if (!psInfo.save()) {
									log.debug("保存产品库存记录失败！！");
									throw new RuntimeException("保存产品库存记录失败!");
								}
							}
						} else {
							log.debug(p.getStr(Product.column_name) + "库存不够，无法购买！！");
							// throw new RuntimeException(p.getStr(Product.column_name)
							// + "库存不够，请先入库！！");
							msg = "药贴库存不足，请联系店员入库";
							flag = false;
						}
							
							
						
					}else if (Integer.parseInt(yt) == 0) {
						
							cd.set(CustomerService.column_plasterCount, yt);
							Date date1 = new Date();
							Date startTime = cd.getDate(CustomerService.column_startTime);
							
							if(sdf.format(date1).equals(sdf.format(startTime))) {  
								 cd.set(CustomerService.column_endTime, date1);
							 }else{
								 cd.set(CustomerService.column_endTime, sdf.parse(sdf.format(startTime)+" 21:00:00"));
							 }
							
							cd.set(CustomerService.column_updateDate, new Date());
							cd.set(CustomerService.column_updateId,customerIds);
							m.put("msg", cd.update());
							
							
						
					}
					
					//保存手法
					if (flag && StringUtils.isNotBlank(sf) ) {
							cd.set(CustomerService.column_isPlaster, "1");
							cd.set(CustomerService.column_userID, sf);
							cd.set(CustomerService.column_plasterServier, sf);
							cd.set(CustomerService.column_updateDate, new Date());
							cd.set(CustomerService.column_updateId, customerIds);
							m.put("msg", cd.update());

					}
					DailyNursingTotal  dnt = DailyNursingTotal.dao.getDnt(organids,cd.getDate(CustomerService.column_startTime));
					if(flag && (StringUtils.isNotBlank(yb)  || StringUtils.isNotBlank(gb)|| StringUtils.isNotBlank(dt) || StringUtils.isNotBlank(xt))){

						CustomerProduct jy = CustomerProduct.dao.findFirst(proSql,customerIds,organids,"95e2ae17462e4d0eb1dc84bc63bc478a");
						CustomerProduct g = CustomerProduct.dao.findFirst(proSql,customerIds,organids,"daaba791f4104ae98504a1bc421e0d8d");
						if(jy!=null && g!=null){//该顾客购买了精油和膏
							ProductOrgExperience poejy = ProductOrgExperience.dao.findFirst(usageSql,organids,"95e2ae17462e4d0eb1dc84bc63bc478a");
							ProductOrgExperience poeg = ProductOrgExperience.dao.findFirst(usageSql,organids,"daaba791f4104ae98504a1bc421e0d8d");
							if(yb!=null && !yb.equals("")){
								if(poejy!=null && poejy.getFloat(ProductOrgExperience.column_ybExperience)!=null){
									ybjyusage = poejy.getFloat(ProductOrgExperience.column_ybExperience);
								}else{
									ybjyusage = 1f;
								}
								
								if(poeg!=null && poeg.getFloat(ProductOrgExperience.column_ybExperience)!=null){
									ybgusage = poeg.getFloat(ProductOrgExperience.column_ybExperience);
								}else{
									ybgusage = 1f;
								}
							}
							if(gb!=null && !gb.equals("")){
								if(poejy!=null && poejy.getFloat(ProductOrgExperience.column_gbExperience)!=null){
									gbjyusage = poejy.getFloat(ProductOrgExperience.column_gbExperience);
								}else{
									gbjyusage = 0.5f;
								}
								
								if(poeg!=null && poeg.getFloat(ProductOrgExperience.column_gbExperience)!=null){
									gbgusage = poeg.getFloat(ProductOrgExperience.column_gbExperience);
								}else{
									gbgusage = 0.5f;
								}			
							}
							if(dt!=null && !dt.equals("")){
								if(poejy!=null && poejy.getFloat(ProductOrgExperience.column_dtExperience)!=null){
									dtjyusage = poejy.getFloat(ProductOrgExperience.column_dtExperience);
								}else{
									dtjyusage = 0.7f;
								}
								
								if(poeg!=null && poeg.getFloat(ProductOrgExperience.column_dtExperience)!=null){
									dtgusage = poeg.getFloat(ProductOrgExperience.column_dtExperience);
								}else{
									dtgusage = 0.7f;
								}		
							}
							if(xt!=null && !xt.equals("")){
								if(poejy!=null && poejy.getFloat(ProductOrgExperience.column_xtExperience)!=null){
									xtjyusage = poejy.getFloat(ProductOrgExperience.column_xtExperience);
								}else{
									xtjyusage = 0.3f;
								}
								
								if(poeg!=null && poeg.getFloat(ProductOrgExperience.column_xtExperience)!=null){
									xtgusage = poeg.getFloat(ProductOrgExperience.column_xtExperience);
								}else{
									xtgusage = 0.3f;
								}		
							}
							
							jysum = ybjyusage+dtjyusage+xtjyusage+gbjyusage;
							gsum = ybgusage+dtgusage+xtgusage+gbgusage;
							
							if(jysum<jy.getFloat(CustomerProduct.column_totalExperience)&&gsum<g.getFloat(CustomerProduct.column_totalExperience)){
								cd.set(CustomerService.column_isShaping, "1");
								cd.update();
								ServiceShaping cs = new ServiceShaping();
								cs.set(ServiceShaping.column_customerIds, customerIds)
								.set(ServiceShaping.column_createDate, new Date())
								.set(ServiceShaping.column_createId,customerIds)
								.set(ServiceShaping.column_organIds, organids)
								.set(ServiceShaping.column_serviceIds, cd.getStr(CustomerService.column_ids))
								.set(ServiceShaping.column_isgk, 1);
								if (StringUtils.isNotBlank(yb)) {
									cs.set(ServiceShaping.column_ybjyusage,ybjyusage);
									cs.set(ServiceShaping.column_ybgusage, ybgusage);
									cs.set(ServiceShaping.column_yb, yb);
								}
								
								if (StringUtils.isNotBlank(gb)) {
									cs.set(ServiceShaping.column_gbjyusage,gbjyusage);
									cs.set(ServiceShaping.column_gbgusage, gbgusage);
									cs.set(ServiceShaping.column_gb, gb);
								}
								
								if (StringUtils.isNotBlank(dt)) {
									cs.set(ServiceShaping.column_dtjyusage,dtjyusage);
									cs.set(ServiceShaping.column_dtgusage, dtgusage);
									cs.set(ServiceShaping.column_dt, dt);
								}
								
								if (StringUtils.isNotBlank(xt)) {
									cs.set(ServiceShaping.column_xtjyusage,xtjyusage);
									cs.set(ServiceShaping.column_xtgusage, xtgusage);
									cs.set(ServiceShaping.column_xt, xt);
								}
								
								m.put("msg", cs.save());
								if(dnt != null)
								{
									dnt.set(DailyNursingTotal.column_sycprs, dnt.getInt(DailyNursingTotal.column_sycprs)+1);
									CustomerDetail cdet = CustomerDetail.dao.findFirst("SELECT * FROM sb_customer_detail WHERE customerIds = ? and dataStatus in ('1','2')",customerIds);
									if(ToolDateTime.format(cdet.getDate(CustomerDetail.column_firstDate), ToolDateTime.pattern_y).equals(ToolDateTime.format(new Date(), ToolDateTime.pattern_y))){
										dnt.set(DailyNursingTotal.column_xgkjhrs, dnt.getInt(DailyNursingTotal.column_xgkjhrs)+1);
									}
								}
							}else{
								msg = "产品不够了，请续产品";
							}
						}else{
							msg = "您还没有购买产品";
						}
						
						
						
					}
					
					
					
				}
				
				
				
			}else{
				msg = "您当天还没有进行体重登记，请先登记体重再保存精护部位";
			}
		}else{
			msg = "此微信号还没绑定顾客，请先绑定";
		}
		}else{
			msg = "验证码错误";
		}
		
		renderText(msg);
	}

	
	
	
	
	
	
	

}
